package org.example.datasource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order(0) // 优先级需高于事务切面
public class DataSourceAspect {

    @Around("@annotation(targetDataSource)")
    public Object switchDataSource(ProceedingJoinPoint joinPoint, TargetDataSource targetDataSource) throws Throwable {
        String originalKey = DataSourceContextHolder.getDataSourceKey();
        String targetKey = targetDataSource.value();
        try {
            // 设置目标数据源
            DataSourceContextHolder.setDataSourceKey(targetKey);
            return joinPoint.proceed();
        } finally {
            // 恢复原始数据源
            if (originalKey != null) {
                DataSourceContextHolder.setDataSourceKey(originalKey);
            } else {
                DataSourceContextHolder.clearDataSourceKey();
            }
        }
    }
}